package com.dynamic.datasource;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Aspect
@Order(value = -999)
@Component
public class DynamicDataSourceAop {
	
	private static final String[] mastMethodPreix = {"getTest1"};
    private static final String[] slaveMethodPreix = {"getTest2"};
    
    
    @Before("execution(* com.dynamic.test.service..*.*(..)) or execution(* com.dynamic.service..*.*(..))")
    public void checkTransaction(JoinPoint joinPoint) {
    	try {
	        String methodName = joinPoint.getSignature().getName();
	        if (StringUtils.startsWithAny(methodName, mastMethodPreix)) {
	        	DynamicDataSourceHolder.setDataSourceKey(DynamicDataSourceHolder.DataSoureKey.MASTER);	
	        } else if((StringUtils.startsWithAny(methodName, slaveMethodPreix))){
	            DynamicDataSourceHolder.setDataSourceKey(DynamicDataSourceHolder.DataSoureKey.SLAVE);
	        }
    	} catch (Exception e) {
    		DynamicDataSourceHolder.setDataSourceKey(DynamicDataSourceHolder.DataSoureKey.MASTER);
    		e.printStackTrace();
		}
    }
}
